Rust 模式匹配
阐述
模式一般由以下内容组合而成:
- 字面值
- 解构的数组、枚举、结构体或者元组
- 变量
- 通配符
- 占位符
let 匹配
let 绑定就是一种匹配:
let (x, y, z) = (1, 2, 3);
if let 或者 while let 匹配
if let Some(3) = v {
println!("three");
}
match 匹配
match target {
模式1 => 表 达式1,
模式2 => {
语句1;
语句2;
表达式2
},
_ => 表达式3
}
matches! 宏
matches! 可以返回一个表达式是否与一个模式匹配。
let foo = 'f';
assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
let bar = Some(4);
assert!(matches!(bar, Some(x) if x > 2));
匹配守卫
在模式后面还可以加上条件判断,这样可以提高表达能力,并且条件判断中的变量不受覆盖影响
fn main() {
let x = Some(5);
let y = 10;
match x {
Some(50) => println!("Got 50"),
Some(n) if n == y => println!("Matched, n = {}", n),
_ => println!("Default case, x = {:?}", x),
}
println!("at the end: x = {:?}, y = {}", x, y);
}
实例
模式列表
- 字面值,如
1 - 变量,如
Some(x) - 多个值,如
1 | 2 - 范围,如
1..=5 - 解构,如
Point { x, y },甚至Point { x, y: 0 } - 数组,如
[x, y],或不定长[x, ..] - 守卫
- @绑定